package order

import (
	"fmt"
	"gin/app/http/common"
	"gin/app/http/global"
	order2 "gin/app/http/model/order"
	"gin/app/http/model/order_detail"
	"gin/app/http/response"
	"gin/app/http/struct/order"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"gorm.io/gorm"
	"math/rand"
	"time"
)

// 创建订单
func CreateOrder(c *gin.Context) {
	DecryptedData, _ := c.Get("DecryptedData")
	var params order.CrateOrder
	if err := binding.JSON.BindBody([]byte(DecryptedData.(string)), &params); err != nil {
		response.Fail(c, "参数不正确！", gin.H{
			"error": err.Error(),
		})
		return
	}

	db := global.DB
	OrderId := GenerateOrderNumber()
	user_id := c.GetInt("user_id")
	insertOrderData := order2.Order{
		OrderId:         OrderId,
		UserId:          user_id,
		OrderDate:       time.Now(),
		TotalAmount:     params.TotalPrice,
		PaymentStatus:   1,
		ShippingAddress: params.ShippingAddress,
	}
	db.Create(&insertOrderData)

	fmt.Println(insertOrderData.OrderId)
	var orderDetailData []order_detail.OrderDetail
	for _, v := range params.Items {
		temp := order_detail.OrderDetail{
			OrderId:   insertOrderData.OrderId,
			ProductId: v.Product_id,
			Quantity:  v.Quantity,
			Price:     v.Price,
		}
		orderDetailData = append(orderDetailData, temp)
	}
	db.Create(&orderDetailData)
	response.Success(c, "请求成功", gin.H{})
}

type orderDetail struct {
	order_detail.OrderDetail
	Name  string `json:"name"`
	Image string `json:"image"`
}

// 订单列表
func GetOrderList(c *gin.Context) {
	DecryptedData, _ := c.Get("DecryptedData")
	var params order.GetOrderList
	if err := binding.JSON.BindBody([]byte(DecryptedData.(string)), &params); err != nil {
		response.Fail(c, "参数不正确！", gin.H{
			"error": err.Error(),
		})
		return
	}

	db := global.DB
	// 执行原生查询
	var Lists []order2.Order
	var result *gorm.DB
	user_id := c.GetInt("user_id")
	if params.PaymentStatus == 0 {
		result = db.Where("user_id=?", user_id).Order("order_date desc").Find(&Lists)
	} else {
		result = db.Where("user_id=? and payment_status=?", user_id, params.PaymentStatus).Order("order_date desc").Find(&Lists)
	}
	if result.Error != nil {
		response.Fail(c, "请求失败", gin.H{})
		return
	}
	var ListsDetail []orderDetail
	sql := "select a.*,zp.name ,zp.image  from (select * from zlg_order_detail where order_id  in (select order_id from zlg_orders where user_id=?))as a join zlg_product zp on a.product_id=zp .id ORDER by order_detail_id DESC"
	db.Raw(sql, user_id).Scan(&ListsDetail)
	ListsDetailNew := common.GroupByField(ListsDetail, "OrderId")
	fmt.Println(ListsDetailNew)
	var resultData []map[string]interface{}
	for _, v := range Lists {
		temp := make(map[string]interface{})
		temp["order_id"] = v.OrderId
		temp["totalPrice"] = v.TotalAmount
		temp["list"] = ListsDetailNew[v.OrderId]
		resultData = append(resultData, temp)
	}
	if result.Error != nil {
		response.Fail(c, "请求失败", gin.H{})
	} else {
		response.Success(c, "请求成功", gin.H{"data": resultData})
	}
}

func GenerateOrderNumber() string {
	// 获取当前时间戳
	timestamp := time.Now().UnixNano() / int64(time.Millisecond)

	// 生成随机数（可选）
	rand.Seed(time.Now().UnixNano())
	randomPart := rand.Intn(1000) // 在0到999之间生成随机数

	// 构建订单编号
	orderNumber := fmt.Sprintf("%d%d", timestamp, randomPart)

	return orderNumber
}
